package com.atjava.webspider.util;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.atjava.webspider.consts.Const;

public class XmlUtil {

	public static String getElementXml(String name,String value){
		StringBuffer xml = new StringBuffer();
		xml.append(getElementStart(name));
		xml.append(value);
		xml.append(getElementEnd(name));
		return xml.toString();
	}
	
	public static String getElementStart(String name){
		StringBuffer xml = new StringBuffer();
		xml.append("<");xml.append(name);xml.append(">");
		return xml.toString();
	}
	
	public static String getElementEnd(String name){
		StringBuffer xml = new StringBuffer();
		xml.append("</");xml.append(name);xml.append(">");
		return xml.toString();
	}
	
	public static String getCdataElementXml(String name,String value){
		StringBuffer xml = new StringBuffer();
		xml.append("<");xml.append(name);xml.append(">");
		xml.append("<![CDATA[\r\n");
		xml.append(value);
		xml.append("\r\n]]>");
		xml.append("</");xml.append(name);xml.append(">");
		return xml.toString();
	}
	
	public static boolean needCdata(String strValue){
		return 
			strValue.indexOf("<") > 0 ||
			strValue.indexOf(">") > 0 || 
			strValue.indexOf("&") > 0;
	}
	
	public static Map<String, String>  readVarMap(File f,String encoding) {
		
		Map<String, String> varMap = new HashMap<String, String>();
		
		if(!isDataFile(f))
			return varMap;
		
		SAXReader reader = new SAXReader();
		reader.setEncoding(encoding);
		
		Document doc = null;
		try {
			doc = reader.read(f);
		} catch (DocumentException e) {
			LogUtil.info("读取数据文件 [ " + f.getAbsolutePath() + " ] 错误！");
		}
		
		if(doc != null){
			Element root = doc.getRootElement();
			List<?> elements = root.elements();
			for (int i = 0; i < elements.size(); i++) {
				Element ele = (Element)elements.get(i);
				String name = ele.getName();
				String value = ele.getText();
				varMap.put(name, value);
			}
		}
		
		return varMap;
	}
	
	public static boolean isDataFile(File f){
		String name = f.getName();
		return 
			StringUtils.countMatches(name, Const.DATA_NAME_SEPARATOR) == 1 &&
			name.length() > 30;
	}
}
